package com.daigou.admin.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daigou.constants.CommonConstants;
import com.daigou.dto.AjaxResult;
import com.daigou.dto.OrderDto;
import com.daigou.dto.OrderQuery;
import com.daigou.dto.PageInfo;
import com.daigou.dto.ServiceResult;
import com.daigou.model.Order;
import com.daigou.model.Product;
import com.daigou.model.Shop;
import com.daigou.model.ShopCustomer;
import com.daigou.model.User;
import com.daigou.service.CustomerService;
import com.daigou.service.OrderService;
import com.daigou.service.ProductService;

@Controller("adminOrderController")
@RequestMapping(value = "/admin")
public class OrderController {
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private CustomerService customerService;
	
	@InitBinder({"order"})
	public void initBinderProduct(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("order.");
	}
	/**
	 * 查看详情和编辑页
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/order/{id}",method = RequestMethod.GET)
    public String toOrderPage(HttpServletRequest request,Model model,@PathVariable("id")String id){
		LOGGER.info("进入订单新增{}",id);
		Order order = null;
		User user = (User)request.getAttribute(CommonConstants.USER_INFO);
		model.addAttribute("user", user);
		if(id == null || id.equals("0")){
			LOGGER.info("进入订单新增{}",id);
			order = new Order();
			order.setId(0L);
			model.addAttribute("order", order);
			return "/admin/app/order_add";
		}else if(id.indexOf("_") >= 0){
			LOGGER.info("进入订单新增{}",id);
			order = new Order();
			order.setId(0L);
			String[] idArray = id.split("_");
			Product product = productService.selectByPrimaryKey(Long.parseLong(idArray[1]));
			if(product != null){
				order.setProductId(product.getId());
				order.setProductName(product.getName());
				order.setSpec(product.getSpec());
				order.setCate(product.getCate());
				order.setBrand(product.getBrand());
				order.setProductionPlace(product.getProductionPlace());
				order.setPicMain(product.getPicMain());
				order.setPrice(product.getSalePrice());
				order.setTotalAmount(product.getSalePrice());
			}
			model.addAttribute("order", order);
			return "/admin/app/order_add";
		}else{
			LOGGER.info("进入订单更新{}",id);
			order = orderService.selectByPrimaryKey(Long.parseLong(id));
			model.addAttribute("order", order);
			if(order.getBuyerCode() != null && !"".equals(order.getBuyerCode())){
				ShopCustomer customer = customerService.selectByShopIdAndMobile(user.getShopId(), Long.parseLong(order.getBuyerCode()));
				model.addAttribute("customer", customer);
			}
			return "/admin/app/order_update";
		}
    }
	/**
	 * 查看详情和编辑页
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/order/{id}/details",method = RequestMethod.GET)
    public String toOrderDetailsPage(Model model,@PathVariable("id")Long id){
		LOGGER.info("进入订单详情{}",id);
		Order order = orderService.selectByPrimaryKey(id);
		model.addAttribute("order", order);
        return "/admin/app/order_details";
    }
	/**
	 * 查看详情和编辑页
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/order/{id}/send",method = RequestMethod.GET)
    public String toOrderSendPage(Model model,@PathVariable("id")Long id){
		LOGGER.info("进入订单发货{}",id);
		Order order = orderService.selectByPrimaryKey(id);
		model.addAttribute("order", order);
        return "/admin/app/order_send";
    }
	/**
	 * 订单删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/order/{id}",method = RequestMethod.DELETE)
	@ResponseBody
    public AjaxResult deleteOrder(HttpServletRequest request,Model model,@PathVariable("id")Long id){
		if(id == null || id.equals(0L)){
			LOGGER.info("进入订单删除{}",id);
			return new AjaxResult(false,"删除失败,请传入订单id!");
		}else{
			LOGGER.info("进入商品更新{}",id);
			int result = orderService.deleteByPrimaryKey(id);
			if(result == 0){
				return new AjaxResult(false,"订单不存在,请刷新后重试!");
			}
			return new AjaxResult(true,"订单删除成功!");
		}
    }
	/**
	 * 新增和修改
	 * @return
	 */
	@RequestMapping(value = "/order",method = RequestMethod.POST)
	@ResponseBody
    public AjaxResult order(HttpServletRequest request,@RequestBody Order order){
		User user = (User)request.getAttribute(CommonConstants.USER_INFO);
		Shop shop = (Shop)request.getAttribute(CommonConstants.SHOP_INFO);
		order.setShopId(shop.getId());
		order.setShopName(shop.getName());
		order.setCreatorId(user.getId());
		order.setCreatedTime(new Date());
		order.setModifierId(user.getId());
		order.setModifiedTime(new Date());
		try{
			ServiceResult serviceResult = orderService.insertOrUpdate(order);
	        return new AjaxResult(serviceResult);
		}catch(Exception ex){
			return new AjaxResult(false,ex.getMessage());
		}
    }
	
	/**
	 * 订单状态修改
	 * @return
	 */
	@RequestMapping(value = "/order-update-status",method = RequestMethod.POST)
	@ResponseBody
    public AjaxResult orderUpdateStatus(HttpServletRequest request,@RequestBody Order order){
		try{
			User user = (User)request.getAttribute(CommonConstants.USER_INFO);
			order.setModifierId(user.getId());
			order.setModifiedTime(new Date());
			order.setPrice(null);
			order.setNum(null);
			order.setTotalAmount(null);
			order.setPayAmount(null);
			order.setDr(null);
			int result = orderService.updateByPrimaryKeySelective(order);
			if(result == 0){
				return new AjaxResult(false,"订单更新失败,请刷新后重试!");
			}
	        return new AjaxResult(true,"订单更新成功!");
		}catch(Exception ex){
			return new AjaxResult(false,ex.getMessage());
		}
    }
	
	@RequestMapping(value = "/order",method = RequestMethod.GET)
    public String toOrderListPage(HttpServletRequest request,Model model){
		LOGGER.info("进入订单列表页面");
		User user = (User)request.getAttribute(CommonConstants.USER_INFO);
		OrderQuery orderQuery = new OrderQuery();
		orderQuery.setShopId(user.getShopId());
		orderQuery.builderTime();
		orderQuery.setUser(user);
		//设置分页
		orderQuery.buildPage("");
		PageInfo<Order> pageInfo = orderService.selectByCondition(orderQuery);
		model.addAttribute("orderList", pageInfo.getRows());
		Integer totalCount = orderService.selectTotalCountByCondition(orderQuery);
		model.addAttribute("totalCount", totalCount);
		Integer caogaoCount = orderService.selectTotalCaogaoByShopId(user.getShopId(), null);
		model.addAttribute("caogaoCount", caogaoCount);
		BigDecimal totalAmount = orderService.selectTotalAmountByCondition(orderQuery);
		model.addAttribute("totalAmount", totalAmount==null?BigDecimal.ZERO:totalAmount);
		BigDecimal payAmount = orderService.selectPayAmountByCondition(orderQuery);
		model.addAttribute("payAmount", payAmount==null?BigDecimal.ZERO:payAmount);
		BigDecimal noPayAmount = orderService.selectNoPayAmountByCondition(orderQuery);
		model.addAttribute("noPayAmount", noPayAmount==null?BigDecimal.ZERO:noPayAmount);
        return "/admin/app/order_list";
    }
	
	@RequestMapping(value = "/order-caogao",method = RequestMethod.GET)
    public String toOrderCaogaoListPage(HttpServletRequest request,Model model){
		LOGGER.info("进入订单列表页面");
		Shop shop = (Shop)request.getAttribute(CommonConstants.SHOP_INFO);
		List<Order> orderList = orderService.selectCaogaoByShopId(shop.getId(),null);
		model.addAttribute("orderList", orderList);
        return "/admin/app/order_caogao";
    }
	
	@RequestMapping(value = "/order-query",method = RequestMethod.POST)
	@ResponseBody
    public AjaxResult queryOrderList(HttpServletRequest request,@RequestBody OrderQuery orderQuery){
		LOGGER.info("查询订单");
		User user = (User)request.getAttribute(CommonConstants.USER_INFO);
		orderQuery.setShopId(user.getShopId());
		orderQuery.builderTime();
		orderQuery.setUser(user);
		//设置分页
		orderQuery.buildPage("");
		PageInfo<Order> pageInfo = orderService.selectByCondition(orderQuery);
		Integer totalCount = orderService.selectTotalCountByCondition(orderQuery);
		Integer caogaoCount = orderService.selectTotalCaogaoByShopId(user.getShopId(), null);
		BigDecimal totalAmount = orderService.selectTotalAmountByCondition(orderQuery);
		BigDecimal payAmount = orderService.selectPayAmountByCondition(orderQuery);
		BigDecimal noPayAmount = orderService.selectNoPayAmountByCondition(orderQuery);
		
		OrderDto orderDto = new OrderDto();
		orderDto.setOrderList(pageInfo.getRows());
		orderDto.setTotalCount(totalCount);
		orderDto.setCaogaoCount(caogaoCount);
		orderDto.setTotalAmount(totalAmount);
		orderDto.setPayAmount(payAmount);
		orderDto.setNoPayAmount(noPayAmount);
		return new AjaxResult(true,orderDto);
    }
	
	//创建Excel
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {

    }
}
